const feishuCrypto = require('../utils/crypto');
const config = require('../../config');

/**
 * 飞书webhook认证中间件
 */
function feishuAuthMiddleware(req, res, next) {
  try {
    // 获取请求头中的签名信息
    const timestamp = req.headers['x-lark-request-timestamp'];
    const nonce = req.headers['x-lark-request-nonce'];
    const signature = req.headers['x-lark-signature'];
    
    // 如果没有签名信息，可能是明文请求
    if (!timestamp || !nonce || !signature) {
      console.log('收到明文请求，跳过签名验证');
      return next();
    }
    
    // 获取请求体
    const body = JSON.stringify(req.body);
    
    // 验证签名
    const isValid = feishuCrypto.verifySignature(timestamp, nonce, body, signature);
    
    if (!isValid) {
      console.error('签名验证失败');
      return res.status(401).json({
        code: 401,
        message: '签名验证失败'
      });
    }
    
    console.log('签名验证成功');
    next();
  } catch (error) {
    console.error('认证中间件错误:', error);
    return res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
}

module.exports = feishuAuthMiddleware; 